package com.hyfrogx.modules.sys.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hyfrogx.common.base.BaseServiceImpl;
import com.hyfrogx.common.base.QueryForm;
import com.hyfrogx.common.exception.MyException;
import com.hyfrogx.modules.sys.entity.SysDictEntity;
import com.hyfrogx.modules.sys.service.SysDictService;
import com.hyfrogx.modules.sys.dao.SysDictDao;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 字典 服务实现类
 * </p>
 *
 * @author wanglei
 * @date 2019-07-15 15:51:11
 */
@Service
public class SysDictServiceImpl extends BaseServiceImpl<SysDictDao, SysDictEntity> implements SysDictService {

	@Override
	public String getIdKey() {
		return "id";
	}

	@Override
	public String getEntityName() {
		return "字典";
	}

	@Override
	public List<String> getUpdateIgnoreKey() {
		return CollUtil.newArrayList("code");
	}

	@Override
	public void beforeSaveOrUpdateEntity(SysDictEntity entity, boolean isNew) {
		super.beforeSaveOrUpdateEntity(entity, isNew);
		if (retBool(this.count(
				new QueryWrapper<SysDictEntity>()
						.eq("code", entity.getCode())
						.ne(!isNew, "id", entity.getId())
		))) {
			throw new MyException("字典代码已存在");
		}
//		if (retBool(this.count(
//				new QueryWrapper<SysDictEntity>()
//						.eq("name", entity.getName())
//						.ne(!isNew, "id", entity.getId())
//		))) {
//			throw new MyException("字典名称已存在");
//		}
	}

	@Override
	public QueryWrapper<SysDictEntity> getSelectWrapper(QueryForm<SysDictEntity> form, boolean isOrder) {
		String name = form.getParamStr("name");
		String code = form.getParamStr("code");
		Integer status = form.getParamInteger("status");
		Integer isAll = form.getParamInteger("isAll");
		return form.getWrapper(isOrder)
				.like(StrUtil.isNotBlank(name), "name", name)
				.like(StrUtil.isNotBlank(code), "code", code)
				.eq(ObjectUtil.notEqual(isAll, 1) && ObjectUtil.isNotNull(status), "status", status)
				;
	}

	@Override
	public SysDictEntity getByCode(String code) {
		return this.getOne(new QueryWrapper<SysDictEntity>().eq("code", code));
	}
}
